package com.mz.mattress.client.plan.impl;

import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.entity.*;
import com.mz.mattress.api.enums.TaskStatusEnum;
import com.mz.mattress.client.api.req.UseOrderReq;
import com.mz.mattress.client.mapper.*;
import com.mz.mattress.client.plan.AbstractPlanExecutor;
import com.mz.mattress.client.service.OrderService;
import com.mz.mattress.client.task.TaskStep;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

//任务步骤处理器

/**
 * 老会员 ，已有订单，直接核销
 * @param
 */
@Slf4j
@Service("checkOrderExecutor")
public class CheckOrderExecutor extends AbstractPlanExecutor {

    public static final String LOG_START = "check_order_{}_taskId={}";

    @Autowired
    private OrderService orderService;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    public CheckOrderExecutor(PlanTaskDataMapper planTaskDataMapper) {
        super(planTaskDataMapper);
    }

    @TaskStep(value = 0, delayTime = 10)
    public void bindDevice(PlanTaskData data) {

        log.info(LOG_START, "bindDevice", data.getId());

        Long orderId = data.getOrderId();

        Order order = orderMapper.selectByOrderId(orderId);
        if (order == null) {
            data.setStatus(TaskStatusEnum.FAILED.getValue());
            data.setRemark("order_not_found");
            return;
        }

        // 需要 记录 在用的设备号，避免 同一个设备 有多个订单在用

        //取出可用设备
        List<String> list = deviceMapper.selectAvailableByMerchantId(order.getMerchantId());
        if (list.isEmpty()) {
            log.error("no_device_available,merchantId=" + order.getMerchantId());
            return;
        }

        String deviceCode = null;
        if (list.size() > 1) {
            int idx = new Random().nextInt(list.size());
            deviceCode = list.get(idx);
        } else {
            deviceCode = list.get(0);
        }

        data.setDeviceCode(deviceCode);
        data.setMerchantId(order.getMerchantId());
        data.setMemberId(order.getMemberId());

        UseOrderReq req = new UseOrderReq();
        req.setOrderId(data.getOrderId());
        req.setDeviceCode(deviceCode);
        req.setMemberId(data.getMemberId());
        req.setDev(2);

        Result<Integer> result = orderService.bindDevice(req);

        //更新记录
        data.setStatus(result.isSuccess() ? TaskStatusEnum.SUCCESS.getValue() : TaskStatusEnum.FAILED.getValue());

    }

    public static void main(String[] args) {

        Random random = new Random();

        for (int i = 0; i < 20; i++) {
            System.out.println(random.nextInt(3));
        }

        System.out.println("d");

    }


}
